`include "define.sv"

module memory_controller #(
    parameter DATA_WIDTH = 128,
    parameter ADDR_WIDTH = 10
)(
    input wire clk,
    input wire rst_n,
    // APB
    input wire [1:0] matrix_type,
    input wire [1:0] data_type,
    // AXI
    input wire                  we, // 直接来自axi_slave的memc_we
    input wire                  re0,re1,re2,
    output reg                  full,          // 添加FIFO满信号
    input wire [DATA_WIDTH-1:0] din, // 直接来自axi_slave的memc_din
    input wire [7:0]            burst_len, 
    
    output reg [DATA_WIDTH-1:0] ram0_dout, ram1_dout, ram2_dout,
    output reg                  ram0_burst_done, ram1_burst_done, ram2_burst_done,
    output reg                  ram0_empty, ram1_empty, ram2_empty // 添加空信号
);

    wire [1:0] current_ram;  
    wire [7:0] ram0_burst_len, ram1_burst_len, ram2_burst_len;
    
    // 添加读选择器
    //wire [1:0] read_ram;
    //wire re0, re1, re2;

    // 突发长度计算器（保持不变）
    ram_burst_len_caculator ram_len (
        .matrix_type(matrix_type),
        .data_type(data_type),
        .matrix_c_transfers(ram0_burst_len),
        .matrix_b_transfers(ram1_burst_len), 
        .matrix_a_transfers(ram2_burst_len)
    );

    // 修改为FIFO选择器
    fifo_selector fifo_selector (
        .clk             (clk),
        .rst_n           (rst_n),
        .we              (we),
        //.re              (re0||re1||re2),
        .ram0_empty      (ram0_empty),
        .ram1_empty      (ram1_empty),
        .ram2_empty      (ram2_empty),
        .ram0_burst_len  (ram0_burst_len),
        .ram1_burst_len  (ram1_burst_len),
        .ram2_burst_len  (ram2_burst_len),
        .current_ram     (current_ram)
        //.read_ram        (read_ram)
    );

    // FIFO实例化
    fifo_burst #(
        .DATA_WIDTH(DATA_WIDTH),
        .FIFO_DEPTH(512)
    ) fifo0 (
        .clk(clk),
        .rst_n(rst_n),
        .wr_en(we && (current_ram == 2'b00)),
        .rd_en(re0),
        .din(din),
        .burst_len(ram0_burst_len),
        .dout(ram0_dout),
        .burst_done(ram0_burst_done),
        .empty(ram0_empty),
        .full(full0)
    );

    fifo_burst #(
        .DATA_WIDTH(DATA_WIDTH),
        .FIFO_DEPTH(512)
    ) fifo1 (
        .clk(clk),
        .rst_n(rst_n),
        .wr_en(we && (current_ram == 2'b01)),
        .rd_en(re1),
        .din(din),
        .burst_len(ram1_burst_len),
        .dout(ram1_dout),
        .burst_done(ram1_burst_done),
        .empty(ram1_empty),
        .full(full1)
    );

    fifo_burst #(
        .DATA_WIDTH(DATA_WIDTH),
        .FIFO_DEPTH(512)
    ) fifo2 (
        .clk(clk),
        .rst_n(rst_n),
        .wr_en(we && (current_ram == 2'b10)),
        .rd_en(re2),
        .din(din),
        .burst_len(ram2_burst_len),
        .dout(ram2_dout),
        .burst_done(ram2_burst_done),
        .empty(ram2_empty),
        .full(full2)
    );
    
    // 组合满信号
    assign full = full0 || full1 || full2;

endmodule